package com.weblog.article.service;

import com.weblog.article.client.UserClient;
import com.weblog.article.dao.TagDao;
import com.weblog.model.article.Article;
import com.weblog.model.article.HotTag;
import com.weblog.model.article.Tag;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.IdWorker;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * tag服务层
 * 
 * @author Administrator
 *
 */
@Service
public class TagService {

	@Autowired
	private TagDao tagDao;
	
	@Autowired
	private IdWorker idWorker;

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private UserClient userClient;



	/**
	 * 增加标签
	 * @param tag
	 */
	@Transactional(rollbackFor = Exception.class)
	public int addTag(Tag tag) {
		Tag tagByTagname = tagDao.findTagByTagnameIgnoreCase(tag.getTagname());
		if(tagByTagname!=null){
			return 0;
		}
		String token = (String) request.getAttribute("claims_admin_A");
		if (token != null && !"".equals(token)) {
			//普通管理员
			Result result = userClient.isAccess("role_tag", "tag_add");
			if ((int) result.getData() == 2) {
				//权限不足
				return 2;
			}
			tag.setId(idWorker.nextId() + "");
			tag.setTimes(0);
			tagDao.save(tag);
			return 1;
		}
		//超级管理员
		tag.setId(idWorker.nextId() + "");
		tag.setTimes(0);
		tagDao.save(tag);
		return 1;

	}


	/**
	 * 条件查询+分页
	 * @param map
	 * @param page
	 * @param size
	 * @return
	 */
	public Page<Tag> PageBySearch(Map<String,Object> map, int page, int size) {
		Specification<Tag> specification = createSpecification(map);
		Pageable pageRequest =  PageRequest.of(page-1, size);
		return tagDao.findAll(specification, pageRequest);
	}



	/**
	 * 查询全部列表
	 * @return
	 */
	public List<Tag> findAll() {
		return tagDao.findAll();
	}

	

	
	/**
	 * 条件查询
	 * @param whereMap
	 * @return
	 */
	public List<Tag> findSearch(Map whereMap) {
		Specification<Tag> specification = createSpecification(whereMap);
		return tagDao.findAll(specification);
	}

	/**
	 * 根据ID查询实体
	 * @param id
	 * @return
	 */
	public Tag findById(String id) {
		return tagDao.findById(id).get();
	}



	/**
	 * 修改
	 * @param tag
	 */
	@Transactional(rollbackFor = Exception.class)
	public int update(Tag tag) {
		String token= (String) request.getAttribute("claims_admin_A");
		if(token!=null && !"".equals(token)){
			//普通管理员
			Result result = userClient.isAccess("role_tag", "tag_update");
			if((int)result.getData()==2){
				return 2;
			}
			tagDao.save(tag);
			return 1;
		}
		tagDao.save(tag);
		return 1;

	}

	/**
	 * 删除
	 * @param id
	 */
	@Transactional(rollbackFor = Exception.class)
	public int deleteById(String id) {
		String token= (String) request.getAttribute("claims_admin_A");
		if(token!=null && !"".equals(token)){
			//普通管理员
			Result result = userClient.isAccess("role_tag", "tag_delete");
			if((int)result.getData()==2){
				return 2;
			}
			Tag tag = tagDao.findById(id).get();
			Set<Article> articles = tag.getArticles();
			for(Article article:articles){
				article.getTags().remove(tag);
			}
			tagDao.updateStateById("0",id);

			return 1;
		}
		Tag tag = tagDao.findById(id).get();
		Set<Article> articles = tag.getArticles();
		for(Article article:articles){
			article.getTags().remove(tag);
		}
		tagDao.updateStateById("0",id);
		return 1;

	}

	/**
	 * 动态条件构建
	 * @param searchMap
	 * @return
	 */
	private Specification<Tag> createSpecification(Map<String,Object> searchMap) {

		return new Specification<Tag>() {

			@Override
			public Predicate toPredicate(Root<Tag> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicateList = new ArrayList<Predicate>();

                // 标签名称
                if (searchMap.get("tagname")!=null && !"".equals(searchMap.get("tagname"))) {
                	predicateList.add(cb.like(root.get("tagname").as(String.class), "%"+(String)searchMap.get("tagname")+"%"));
                }
				/**
				 * state：0弃用 1使用
				 * 在查询中，1可使用 0全部
				 */
                if (searchMap.get("state")!=null && !"".equals(searchMap.get("state"))) {
                	String state= (String) searchMap.get("state");
                	if("1".equals(state)){
						predicateList.add(cb.equal(root.get("state").as(String.class), (String)searchMap.get("state")));
					}
                }
				
				return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));

			}
		};

	}

	/**
	 * 查询前三个标签
	 * @param page
	 * @param size
	 * @return
	 */
    public Page<Tag> selectTop3(int page, int size) {
		Pageable pageable=PageRequest.of(page-1,size);
		return tagDao.findTagsByState("1",pageable);
    }

	/**
	 * 查询前15个热门标签
	 * @return
	 */
	public List<HotTag> hotTags20(){
		List<Tag> tags = tagDao.findTop15ByStateOrderByTimesDesc("1");
		List<HotTag>hotList=new ArrayList<>();
		for(Tag tag:tags){
			hotList.add(new HotTag(tag.getTimes(),tag.getTagname()));
		}
		return hotList;
	}
}
